#include <stdio.h>
#include <stdlib.h>

void spiral_print(int ** matrix, int m, int n) 
{
	if (m <= 0 || n <= 0)
		return;

	int count = 0;
	int level = 0;

	while (count < m*n) {
		for(int s = level; s != n-level; ++s) {
			printf("%d ", matrix[level][s]);
			count++;
		}
		if (count >= m*n)
			break;

		for(int s = level + 1; s != m-level; ++s) {
			printf("%d ", matrix[s][n-1-level]);
			count++;
		}
		if (count >= m*n)
			break;

		for(int s = n-level-2; s >= 0; --s) {
			printf("%d ", matrix[m-1-level][s]);
			count++;
		}
		if (count >= m*n)
			break;
	
		for(int s = m-level-2; s >= 1; --s) {
			printf("%d ", matrix[s][level]);
			count++;
		}
		
		if (count >= m*n)
			break;

		level++;
	}

	printf("\n");
}

int main()
{
	int M = 10;
	int N = 3;

	int ** matrix = (int **) malloc(sizeof(int*) * M);
	for (int i = 0; i < M; ++i)
		matrix[i] = (int *) malloc(sizeof(int) * N);

	for (int i = 0; i < M; ++i){
		for (int j = 0; j < N; ++j) {
			matrix[i][j] = i+(j<<1);
			printf("%d ", matrix[i][j]);
		}
		printf("\n");
 	}

	spiral_print(matrix, M, N);
	return 0;
}
